﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CodeGame.Networking.Clientside.ServerClientPackets
{
    class ScriptedPacket : ClientPacket
    {
        private int ID;
        private string Data;

        private static Dictionary<int, string> HookLinks = new Dictionary<int, string>();

        public static void AddHook(int id, HookObject obj)
        {
            ScriptedPacket.HookLinks.Add(id, "NETHOOK_" + id.ToString());
            Singletons.Hooks.Add("NETHOOK_" + id.ToString(), obj);
        }

        public override ServerClientNet GetID()
        {
            return ServerClientNet.ScriptedPacket;
        }

        public override bool Validate(Lidgren.Network.NetIncomingMessage msg)
        {
            this.ID = msg.ReadInt32();
            this.Data = msg.ReadString();

            if (!this.ValidateInt(this.ID))
            {
                return false;
            }

            if (!this.ValidateString(this.Data))
            {
                return false;
            }

            return true;
        }

        public override void Handle()
        {
            Singletons.Hooks.Call("ScriptedHook", this.ID.ToString(), this.Data, null);

            if (ScriptedPacket.HookLinks.ContainsKey(this.ID))
            {
                Singletons.Hooks.Call(ScriptedPacket.HookLinks[this.ID], this.Data, null, null);
            }
        }

        public override void Handle(Lidgren.Network.NetIncomingMessage message)
        {
            this.Validate(message);
            this.Handle();
        }
    }
}
